package network.impl;

import java.util.Queue;


import sharedGameLogic.gameData.BattleResult;
import model.IServerNetwork;
import network.INetwork;
import network.ModelListener;
import network.ServerNetworkListener;

/**
 * 
 * @author Tomas
 *
 */
public class Network implements ModelListener, INetwork {

	private NetServer netServer;
	private IServerNetwork model;
	
	/**
	 * 
	 * @param model
	 * @param port
	 * @param listener
	 * @return
	 */
	public static INetwork getNewInstance(IServerNetwork model, 
											   int port, 
											   ServerNetworkListener listener){
		
		return new Network(model, port, listener);
	}
	
	private Network(IServerNetwork model, int port, ServerNetworkListener listener) {
		this.model = model;
		netServer = new NetServer(port);
		netServer.addNetworkListener(listener);
	}
	
	@Override
	public void start() {
		netServer.start();
	}
	
	@Override
	public void shutDown() {
		netServer.shutDown();
	}
	
	@Override
	public void modelChanged() {
		Object obj = model.getData();
		
		if (obj instanceof Queue<?>) {
			Queue<?> queue = (Queue<?>) obj;
			if (queue.peek() instanceof BattleResult) {
				BattleResult result = (BattleResult) queue.peek();
				//TODO: Remove println!
				System.out.println("Player1 action: " + result.getFirstPlayer().getActionType().toString());
				System.out.println("Player2 action: " + result.getSecondPlayer().getActionType().toString());
				netServer.sendToAll(result);
			} else {
				System.out.println("FAIL!");
			}
		} else {
			netServer.sendToAll(obj);
		}
		
	}

	@Override
	public ModelListener getAsModelListener() {
		return this;
	}
}
